<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getDeliveryDataApi, updateDeliveryApi } from "@/api/delivery-manage"
import { type DeliveryData, type UpdateDeliveryRequestData } from "@/api/delivery-manage/types/delivery"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "DeliveryInfo"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 修改配送员信息
const DEFAULT_FORM_DATA: UpdateDeliveryRequestData = {
  id: 0,
  name: "",
  phone: "",
  idCard: "",
  studentCard: "",
  workStatus: undefined
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<UpdateDeliveryRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<UpdateDeliveryRequestData> = {
  name: [{ required: true, trigger: "blur", message: "请输入姓名" }],
  phone: [{ required: true, trigger: "blur", message: "请输入手机号" }],
  idCard: [{ required: true, trigger: "blur", message: "请输入身份证号" }]
}

const handleUpdate = (row: DeliveryData) => {
  dialogVisible.value = true
  formData.value = {
    id: row.id,
    name: row.name,
    phone: row.phone,
    idCard: row.idCard,
    studentCard: row.studentCard,
    workStatus: row.workStatus
  }
}

const handleUpdateSubmit = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    updateDeliveryApi(formData.value)
      .then(() => {
        ElMessage.success("修改成功")
        dialogVisible.value = false
        getDeliveryData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

// 查询配送员信息数据
const deliveryData = ref<DeliveryData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  phone: "",
  workStatus: ""
})

const getDeliveryData = () => {
  loading.value = true
  getDeliveryDataApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    phone: searchData.phone || undefined,
    workStatus: searchData.workStatus ? Number(searchData.workStatus) : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      deliveryData.value = data.list
    })
    .catch(() => {
      deliveryData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getDeliveryData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getDeliveryData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="workStatus" label="工作状态">
          <el-select v-model="searchData.workStatus" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="可接单" value="1" />
            <el-option label="休息中" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- 不需要新增和删除按钮 -->
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getDeliveryData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="deliveryData">
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column label="身份证" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.idCard" 
                :src="scope.row.idCard" 
                style="width: 50px; height: 50px" 
                fit="cover"
                :preview-src-list="[scope.row.idCard]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
                <template #error>
                  <el-icon>
                    <Loading />
                  </el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="学生证" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.studentCard" 
                :src="scope.row.studentCard" 
                style="width: 50px; height: 50px" 
                fit="cover"
                :preview-src-list="[scope.row.studentCard]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
                <template #error>
                  <el-icon>
                    <Loading />
                  </el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="账户余额" align="center">
            <template #default="scope">
              <span>{{ scope.row.balance ? `¥${scope.row.balance}` : '¥0.00' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="workStatus" label="工作状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.workStatus === 1" type="success" effect="plain" disable-transitions>可接单</el-tag>
              <el-tag v-else type="info" effect="plain" disable-transitions>休息中</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 修改配送员信息 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改配送员信息"
      @closed="resetForm"
      width="40%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="formData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="workStatus" label="工作状态">
          <el-radio-group v-model="formData.workStatus">
            <el-radio :label="1">可接单</el-radio>
            <el-radio :label="2">休息中</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: center;
}
</style>